import { onUnmounted, reactive, ref } from "vue";
import { getRequest, postRequest } from "@/api/baseRequest";
import { i18n } from "@/i18n";
import { ElMessage } from "element-plus";
import { useThrottleFn } from "@vueuse/core";

interface PhoneValidateForm {
  phoneNumber: string;
  code: string;
}

export function usePhoneVerification(emit: (event: "update:value", value: string | null) => void) {
  // 状态管理
  const phoneValidateCodeBtnText = ref<string>(i18n.global.t("rform.phoneVerification.smsCode"));
  // 发送按钮禁用
  const sendCodeBtnDisabled = ref<boolean>(false);
  // 发送状态
  const sendStatus = ref<boolean | null>(null);
  // 验证成功
  const validateSuccess = ref<boolean>(false);
  const loading = ref<boolean>(false);
  const errorMsg = ref<string>("");

  const phoneValidateForm = reactive<PhoneValidateForm>({
    phoneNumber: "",
    code: ""
  });

  // 倒计时相关
  let timer: NodeJS.Timer | null = null;
  const countdown = ref<number>(60);

  // 手机号码验证
  const validatePhone = (phone: string): boolean => {
    const mPattern = /^(?:0|86|\+86)?1[3456789]\d{9}$/;
    if (!phone) {
      errorMsg.value = i18n.global.t("rform.phoneVerification.phoneRequired");
      return false;
    }
    if (!mPattern.test(phone)) {
      errorMsg.value = i18n.global.t("rform.phoneVerification.phoneInvalid");
      return false;
    }
    return true;
  };

  // 开始倒计时
  const startCountdown = () => {
    sendCodeBtnDisabled.value = true;
    timer = setInterval(() => {
      countdown.value--;
      phoneValidateCodeBtnText.value = i18n.global.t("rform.phoneVerification.resend") + `(${countdown.value})`;

      if (countdown.value <= 0) {
        clearInterval(timer);
        resetCountdown();
      }
    }, 1000);
  };

  // 重置倒计时
  const resetCountdown = () => {
    countdown.value = 60;
    sendCodeBtnDisabled.value = false;
    phoneValidateCodeBtnText.value = i18n.global.t("rform.phoneVerification.smsCode");
  };

  // 发送验证码
  const sendValidateMsgHandle = useThrottleFn(async () => {
    errorMsg.value = "";
    if (!validatePhone(phoneValidateForm.phoneNumber)) {
      return;
    }

    try {
      loading.value = true;
      await getRequest(`/form/common/phone/code?phoneNumber=${phoneValidateForm.phoneNumber}`);
      sendStatus.value = true;
      startCountdown();
      ElMessage.success(i18n.global.t("rform.phoneVerification.codeSent"));
    } catch (error) {
      errorMsg.value = i18n.global.t("rform.phoneVerification.sendFailed");
    } finally {
      loading.value = false;
    }
  }, 1000);

  // 验证码校验
  const validateCodeHandle = async () => {
    if (!phoneValidateForm.code) {
      errorMsg.value = i18n.global.t("rform.phoneVerification.codeRequired");
      return;
    }

    try {
      const { data } = await postRequest("/form/common/phone/code/check", phoneValidateForm);
      sendStatus.value = null;
      emit("update:value", data);
      resetCountdown();
      if (timer) {
        clearInterval(timer as NodeJS.Timeout);
      }
      validateSuccess.value = true;
      ElMessage.success(i18n.global.t("rform.phoneVerification.verifySuccess"));
    } catch (error) {}
  };

  // 重新发送
  const handleReSend = () => {
    phoneValidateForm.phoneNumber = "";
    phoneValidateForm.code = "";
    emit("update:value", phoneValidateForm.phoneNumber);
    validateSuccess.value = false;
    errorMsg.value = "";
  };

  // 组件销毁时清理定时器
  onUnmounted(() => {
    if (timer) {
      clearInterval(timer as NodeJS.Timeout);
    }
  });

  return {
    phoneValidateCodeBtnText,
    sendCodeBtnDisabled,
    sendStatus,
    validateSuccess,
    loading,
    errorMsg,
    phoneValidateForm,
    validateCodeHandle,
    handleReSend,
    sendValidateMsgHandle
  };
}
